const koa = require("koa");
const router = require("../router");
const bodyparser = require("koa-bodyparser");
const session = require("koa-session");
const multer = require("koa-multer");
const websocket = require("koa-websocket");
const {
  NAME_PASSWORD_REQUIRED,
  TOKEN_VALID,
  HAS_NOTAUTHOUPDATE,
} = require("./constants");
let app = new koa();
app.use(
  session(
    {
      key: "sessionid",
      maxAge: 10 * 1000,
      signed: true,
    },
    app
  )
);
app.keys = ["yzhsinged"];
//处理json和Urlencoded
app.use(bodyparser());

app = websocket(app);

//当需要处理文件上传时，这个一定不要写(处理form-data)
// const upload = multer();
// app.use(upload.any());

router(app);

app.on("error", (err, ctx, next) => {
  const message = err.message;
  switch (message) {
    case NAME_PASSWORD_REQUIRED:
      ctx.status = 400;
      ctx.body = "用户名和密码不能为空";
      break;
    case TOKEN_VALID:
      ctx.status = 401;
      ctx.body = "token失效";
      break;
    case HAS_NOTAUTHOUPDATE:
      ctx.status = 401;
      ctx.body = "你没有修改此动态的权限";
      break;
    default:
      ctx.status = 404;
      ctx.body = "404了";
  }
});
module.exports = app;
